package com.huike.web.controller.universal;

import com.huike.common.core.domain.AjaxResult;
import com.huike.common.result.FileDownloadAjaxResult;
import com.huike.common.utils.StringUtils;
import com.huike.common.utils.file.AliOssUtil;
import com.huike.common.utils.file.FileUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/**
 * @Description TODO
 * @Author liu
 * @Date 2023-07-11 14:29
 */

@Api(tags = "通用相关接口")
@Slf4j
@RequestMapping("/common")
@RestController
public class universalController {

    @Resource
    private AliOssUtil aliOssUtil;

    @GetMapping("/download")
    @ApiOperation("通用下载接口")
    public FileDownloadAjaxResult download(HttpServletRequest request, HttpServletResponse response, String fileName) {
       log.info("通用下载接口....");
        try {
            // 设置下载文件的路径（根据实际情况修改）
            String filePath = "" + fileName;

            File file = new File(filePath);
            if (!file.exists()) {
                throw new FileNotFoundException("文件不存在");
            }

            // 设置响应头部信息
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            response.setContentType("application/octet-stream");
            response.setContentLength((int) file.length());

            // 创建输入流，读取文件内容
            FileInputStream fis = new FileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(fis);

            // 创建输出流，写入响应
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = bis.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            // 关闭流
            bis.close();
            fis.close();
            outputStream.flush();
            outputStream.close();

            // 文件下载成功，返回成功结果
            return new FileDownloadAjaxResult(200, "文件下载成功");

        } catch (Exception e) {
            log.error("下载文件失败", e);

            // 文件下载失败，返回失败结果
            return new FileDownloadAjaxResult(500, "文件下载失败");
        }
    }


    /**
     * 文件上传接口
     *
     * @param
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation("通用文件上传接口")
    public AjaxResult upload(MultipartFile file) throws IOException {
        log.info("文件上传接口:{}", file);
        //获取原始文件
        String originalFilename = file.getOriginalFilename();
        //获取后缀
        String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
        //设置上传文件名=UUID+原始文件名后缀
        String fileName = UUID.randomUUID().toString().replace("-", "") + extName;
        //调用工具类实现文件上传
        String path = aliOssUtil.upload(file.getBytes(), fileName);
        //返回
        return AjaxResult.success(path);
    }


}
